/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package cn.ac.iie.di.ftp;

import cn.ac.iie.di.global.GlobalParas;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.net.PrintCommandListener;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
import org.apache.log4j.Logger;
import org.apache.commons.io.FileUtils;

/**
 *
 * @author root
 */
public class FtpTools {

    private static Logger logger = Logger.getLogger(FtpTools.class);

    //test
    public static void main(String[] args) {
        while (true) {
            List<String> file = new FtpTools().downFile("192.168.11.96", 21, "qinjia", "qinjia", "/home/qinjia/666", "C:\\Users\\Austin\\Desktop\\");

//            new FtpTools().deleteFile("192.168.11.96", 21, "qinjia", "qinjia", "/home/qinjia/666", file);
        }
    }

    public List downFile(String url, int port, String username, String password, String remotePath, String localPath) {
        List downloadFile = new ArrayList<String>();
        boolean success = false;
        FTPClient ftp = new FTPClient();
        try {
            int reply;
            ftp.connect(url, port);
//            ftp.connect(url);
            //如果采用默认端口，可以使用ftp.connect(url)的方式直接连接FTP服务器
            ftp.login(username, password);//登录
            ftp.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out)));
            reply = ftp.getReplyCode();
            logger.info(url + " reply: " + reply);
            if (!FTPReply.isPositiveCompletion(reply)) {
                logger.info(url + " if (!FTPReply.isPositiveCompletion(reply)) {");
                ftp.disconnect();
                logger.info(url + " ftp login err!username=" + username + ",password=" + password);
                return downloadFile;
            }

            ftp.enterLocalPassiveMode();//在linux上，由于安全限制，可能某些端口没有开启，所以就出现阻塞.开通一个端口来传输数据
            boolean activeFlag = false;
            ftp.setFileType(FTP.BINARY_FILE_TYPE);
            boolean changeWorkingDirectory = ftp.changeWorkingDirectory(remotePath); //转移到FTP服务器目录
            logger.debug(url + " 切换目录：" + changeWorkingDirectory + " ,下载路径：" + remotePath);
            try {
                FTPFile[] fs0 = ftp.listFiles();
//                logger.info(url + "  path :" + remotePath + " ftp list size is " + fs0.length);
                List fileName = new ArrayList<String>();
                for (FTPFile f : fs0) {
                    fileName.add(f.getName());
                }
//                logger.info("xxxxxxxxx" + fileName.toString());
                Long startTime = System.currentTimeMillis();
                Long fileSize = 0L;
                for (FTPFile f : fs0) {
                    OutputStream is = null;
                    try {
                        File rootDir = new File(localPath);
                        if (!rootDir.exists()) {
                            rootDir.mkdirs();
                        }
                        if (!f.getName().endsWith(".log")) {
                            continue;
                        }
                        if (!(f.getName().hashCode() % GlobalParas.HashCode == GlobalParas.EndCode)) {
                            continue;
                        }

                        //标志正在传输 
//                        if (f.getName().endsWith(".temp")) {
//                            continue;
//                        }
                        if (fileName.size() > 100) {
                            Long endTime = System.currentTimeMillis();
                            logger.info("downTime is " + (endTime - startTime) + " downFile is " + fileName.size() + "downFile Size " + fileSize);
                            return fileName;
                        }

                        File localFile = new File(localPath + File.separator + f.getName());
                        is = new FileOutputStream(localFile);
                        boolean retrieveFile = false;
                        while (!ftp.retrieveFile(f.getName(), is)) {
                            logger.info("file :" + f.getName() + " Retry");
                        }
                        retrieveFile = true;
                        if (retrieveFile) {
                            fileSize += localFile.length();
                            File newFile = new File(GlobalParas.TMP_GWX);
                            FileUtils.copyFileToDirectory(localFile, newFile, true);
                            FileUtils.deleteQuietly(localFile);
                            downloadFile.add(f.getName());
                            success = true;
                        }
//                        logger.info(url + " " + f.getName() + " download sucess!");
                    } catch (Exception ex) {
                        logger.error(url + " " + f.getName() + " download err!" + ex, ex);
                    } finally {
                        if (is != null) {
                            try {
                                is.flush();
                                is.close();
                            } catch (Exception e) {
                            }
                        }
                    }
                }
                Long endTime = System.currentTimeMillis();
                logger.info("downTime is " + (endTime - startTime) + " downFile is " + fileName.size() + "downFile Size " + fileSize);
            } catch (Exception e) {
                logger.error(url + " ftp.listFiles error. " + e.getMessage(), e);
                activeFlag = true;
            } finally {
                if (activeFlag) {
                    ftp.enterLocalActiveMode();
//                    ftp.enterLocalPassiveMode();//在linux上，由于安全限制，可能某些端口没有开启，所以就出现阻塞.开通一个端口来传输数据
                    logger.info(url + " current getDataConnectionMode: " + ftp.getDataConnectionMode());
                }
            }
            ftp.logout();
        } catch (Exception e) {
            logger.error(url + " ftp download err " + e.getMessage(), e);
        } finally {
            if (ftp.isConnected()) {
                try {
                    ftp.disconnect();
                } catch (IOException ioe) {
                    logger.error(url + " " + ioe.getMessage(), ioe);
                }
            }
        }
        logger.info(url + " ftp download finish!");
        return downloadFile;
    }

    //计数下载100个json文件
    public boolean downJsonFile(String url, int port, String username, String password, String remotePath, String localPath, String[] filename) {
        logger.info("FtpTools downJsonFile start");
        boolean success = false;
        FTPClient ftp = new FTPClient();
        try {
            int reply;
            ftp.connect(url, port);
            //如果采用默认端口，可以使用ftp.connect(url)的方式直接连接FTP服务器
            ftp.login(username, password);//登录
            ftp.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out)));
            reply = ftp.getReplyCode();
            logger.info(url + " reply: " + reply);
            if (!FTPReply.isPositiveCompletion(reply)) {
                logger.info("if (!FTPReply.isPositiveCompletion(reply)) {");
                ftp.disconnect();
                logger.info(url + " ftp login err!username=" + username + ",password=" + password);
                return success;
            }
            logger.info(url + " current getDataConnectionMode: " + ftp.getDataConnectionMode());
            ftp.enterLocalPassiveMode();//在linux上，由于安全限制，可能某些端口没有开启，所以就出现阻塞.开通一个端口来传输数据
            //设置为主动
//            ftp.enterLocalActiveMode();
            logger.info(url + " current getDataConnectionMode: " + ftp.getDataConnectionMode());

            boolean activeFlag = false;
            try {
                FTPFile[] fs0 = ftp.listFiles();
                logger.info(url + " ftp list size is " + fs0.length);
            } catch (Exception e) {
                logger.error(url + " ftp.listFiles error. " + e.getMessage(), e);
                activeFlag = true;
            } finally {
                if (activeFlag) {
                    ftp.enterLocalActiveMode();
//                    ftp.enterLocalPassiveMode();//在linux上，由于安全限制，可能某些端口没有开启，所以就出现阻塞.开通一个端口来传输数据
                    logger.info(url + " current getDataConnectionMode: " + ftp.getDataConnectionMode());
                }
            }

            ftp.setFileType(FTP.BINARY_FILE_TYPE);
            boolean changeWorkingDirectory = ftp.changeWorkingDirectory(remotePath); //转移到FTP服务器目录
            logger.debug(url + " 切换目录：" + changeWorkingDirectory + " ,下载路径：" + remotePath);
            if (!changeWorkingDirectory) {
                ftp.logout();
                ftp.disconnect();
                logger.info(url + " ftp changeWorkingDirectory failed.");
                return success;
            }

            for (String ff : filename) {
                OutputStream is = null;
                try {
                    File rootDir = new File(localPath);
                    if (!rootDir.exists()) {
                        rootDir.mkdirs();
                    }
                    File localFile = new File(localPath + "/" + ff);
                    is = new FileOutputStream(localFile);
                    boolean retrieveFile = ftp.retrieveFile(ff, is);
                    if (retrieveFile) {
                        logger.info(url + " " + ff + " download sucess!");
                        success = true;
                    } else {
                        logger.info(url + " " + ff + " download error! Retry");
                        boolean fl = ftp.retrieveFile(ff, is);
                        logger.info(url + " " + ff + " download return " + fl + " !");
                        if (fl) {
                            success = true;
                        } else {
                            success = false;
                        }
                    }
                } catch (Exception ex) {
                    logger.error(url + " " + ff + " download err!" + ex.getMessage(), ex);
                } finally {
                    if (is != null) {
                        try {
                            is.close();
                        } catch (Exception e) {
                        }
                    }
                }
            }
            ftp.logout();
        } catch (Exception e) {
            logger.error(url + " ftp download err " + e.getMessage(), e);
        } finally {
            if (ftp.isConnected()) {
                try {
                    ftp.disconnect();
                } catch (IOException ioe) {
                    logger.error(url + " " + ioe.getMessage(), ioe);
                }
            }
        }
        logger.info(url + " ftp download finish!");
        return success;
    }

    //ftp上传dwd文件
    public boolean dwdFile(String url, int port, String username, String password, String remotePath, String fileName, String namespace) {
        boolean success = false;
        FTPClient ftp = new FTPClient();

        try {
            int reply;
            ftp.connect(url, port);
            //如果采用默认端口，可以使用ftp.connect(url)的方式直接连接FTP服务器
            ftp.login(username, password);//登录
            ftp.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out)));
            reply = ftp.getReplyCode();
            logger.info(url + " reply: " + reply);
            if (!FTPReply.isPositiveCompletion(reply)) {
                logger.info(url + " if (!FTPReply.isPositiveCompletion(reply)) {");
                ftp.disconnect();
                logger.info(url + " ftp login err!username=" + username + ",password=" + password);
                return success;
            }

            logger.info(url + " current getDataConnectionMode: " + ftp.getDataConnectionMode());
            ftp.enterLocalPassiveMode();//在linux上，由于安全限制，可能某些端口没有开启，所以就出现阻塞.开通一个端口来传输数据
            //设置为主动
//            ftp.enterLocalActiveMode();
            logger.info(url + " current getDataConnectionMode: " + ftp.getDataConnectionMode());

            boolean activeFlag = false;
            try {
                FTPFile[] fs0 = ftp.listFiles();
                logger.info(url + " ftp list size is " + fs0.length);
            } catch (Exception e) {
                logger.error(url + " ftp.listFiles error. " + e.getMessage(), e);
                activeFlag = true;
            } finally {
                if (activeFlag) {
                    ftp.enterLocalActiveMode();
//                    ftp.enterLocalPassiveMode();//在linux上，由于安全限制，可能某些端口没有开启，所以就出现阻塞.开通一个端口来传输数据
                    logger.info(url + " current getDataConnectionMode: " + ftp.getDataConnectionMode());
                }
            }

            ftp.setFileType(FTP.BINARY_FILE_TYPE);
            boolean changeWorkingDirectory = ftp.changeWorkingDirectory(remotePath); //转移到FTP服务器目录
            logger.debug(url + " 切换目录：" + changeWorkingDirectory + " ,上传路径：" + remotePath);
            if (!changeWorkingDirectory) {
                ftp.logout();
                ftp.disconnect();
                logger.info(url + " ftp changeWorkingDirectory failed.");
                return success;
            }

            InputStream dwd = null;
            try {
                logger.debug(url + " upload dwd file");
                //upload dwd file
                dwd = new ByteArrayInputStream("ok".getBytes("utf-8"));
                boolean flag = ftp.storeFile(fileName + "." + namespace + ".dwd", dwd);
                if (flag) {
                    logger.info(url + " " + fileName + "." + namespace + ".dwd" + " uplaod sucess!");
                    success = true;
                } else {
                    logger.info(url + " " + fileName + "." + namespace + ".dwd" + " uplaod error! Retry");
                    boolean fl = ftp.storeFile(fileName + "." + namespace + ".dwd", dwd);
                    logger.info(url + " " + fileName + "." + namespace + ".dwd" + " uplaod return " + fl + "!");
                    if (fl) {
                        success = true;
                    } else {
                        success = false;
                    }
                }

            } catch (Exception ex) {
                logger.error(url + " " + remotePath + " upload err!" + ex.getMessage(), ex);
            } finally {
                if (dwd != null) {
                    try {
                        dwd.close();
                    } catch (Exception e) {
                    }
                }
            }
            ftp.logout();
        } catch (Exception e) {
            logger.error(url + " ftp upload err " + e.getMessage(), e);
        } finally {
            if (ftp.isConnected()) {
                try {
                    ftp.disconnect();
                } catch (IOException ioe) {
                    logger.error(url + " " + ioe.getMessage(), ioe);
                }
            }
        }
        return success;
    }

    public boolean uploadDwdFile(String url, int port, String username, String password, String remotePath, List<String> fileNames) {
        boolean success = false;
        FTPClient ftp = new FTPClient();

        try {
            int reply;
            ftp.connect(url, port);
            //如果采用默认端口，可以使用ftp.connect(url)的方式直接连接FTP服务器
            ftp.login(username, password);//登录
            ftp.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out)));
            reply = ftp.getReplyCode();
            logger.info(url + " reply: " + reply);
            if (!FTPReply.isPositiveCompletion(reply)) {
                logger.info(url + " if (!FTPReply.isPositiveCompletion(reply)) {");
                ftp.disconnect();
                logger.info(url + " ftp login err!username=" + username + ",password=" + password);
                return success;
            }

//            logger.info(url + " current getDataConnectionMode: " + ftp.getDataConnectionMode());
            ftp.enterLocalPassiveMode();//在linux上，由于安全限制，可能某些端口没有开启，所以就出现阻塞.开通一个端口来传输数据
            //设置为主动
//            ftp.enterLocalActiveMode();
//            logger.info(url + " current getDataConnectionMode: " + ftp.getDataConnectionMode());

            boolean activeFlag = false;
//            try {
//                FTPFile[] fs0 = ftp.listFiles();
////                logger.info(url + " ftp list size is " + fs0.length);
//            } catch (Exception e) {
//                logger.error(url + " ftp.listFiles error. " + e.getMessage(), e);
//                activeFlag = true;
//            } finally {
//                if (activeFlag) {
//                    ftp.enterLocalActiveMode();
////                    ftp.enterLocalPassiveMode();//在linux上，由于安全限制，可能某些端口没有开启，所以就出现阻塞.开通一个端口来传输数据
////                    logger.info(url + " current getDataConnectionMode: " + ftp.getDataConnectionMode());
//                }
//            }

            ftp.setFileType(FTP.BINARY_FILE_TYPE);
            boolean changeWorkingDirectory = ftp.changeWorkingDirectory(remotePath); //转移到FTP服务器目录
//            logger.debug(url + " 切换目录：" + changeWorkingDirectory + " ,上传路径：" + remotePath);
            if (!changeWorkingDirectory) {
                ftp.logout();
                ftp.disconnect();
                logger.info(url + " ftp changeWorkingDirectory failed.");
                return success;
            }
            for (String fileName : fileNames) {
                InputStream dwd = null;
                try {
                    logger.debug(url + " upload dwd file");
                    //upload dwd file
                    dwd = new ByteArrayInputStream("ok".getBytes("utf-8"));
                    boolean flag = ftp.storeFile(fileName + ".dwd", dwd);
                    if (flag) {
                        logger.info(url + " " + fileName + ".dwd" + " uplaod sucess!");
                        success = true;
                    } else {
                        logger.info(url + " " + fileName + ".dwd" + " uplaod error! Retry");
                        boolean fl = ftp.storeFile(fileName + ".dwd", dwd);
                        logger.info(url + " " + fileName + ".dwd" + " uplaod return " + fl + "!");
                        if (fl) {
                            success = true;
                        } else {
                            success = false;
                        }
                    }

                } catch (Exception ex) {
                    logger.error(url + " " + remotePath + " upload err!" + ex.getMessage(), ex);
                } finally {
                    if (dwd != null) {
                        try {
                            dwd.close();
                        } catch (Exception e) {
                        }
                    }
                }
            }

            ftp.logout();
        } catch (Exception e) {
            logger.error(url + " ftp upload err " + e.getMessage(), e);
        } finally {
            if (ftp.isConnected()) {
                try {
                    ftp.disconnect();
                } catch (IOException ioe) {
                    logger.error(url + " " + ioe.getMessage(), ioe);
                }
            }
        }
        return success;
    }

    public boolean deleteFile(String url, int port, String username, String password, String remotePath, List<String> fileNames) {
        boolean success = false;
        FTPClient ftp = new FTPClient();

        try {
            int reply;
            ftp.connect(url, port);
            //如果采用默认端口，可以使用ftp.connect(url)的方式直接连接FTP服务器
            ftp.login(username, password);//登录
            ftp.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out)));
            reply = ftp.getReplyCode();
            logger.info(url + " reply: " + reply);
            if (!FTPReply.isPositiveCompletion(reply)) {
                logger.info(url + " if (!FTPReply.isPositiveCompletion(reply)) {");
                ftp.disconnect();
                logger.info(url + " ftp login err!username=" + username + ",password=" + password);
                return success;
            }

//            logger.info(url + " current getDataConnectionMode: " + ftp.getDataConnectionMode());
            ftp.enterLocalPassiveMode();//在linux上，由于安全限制，可能某些端口没有开启，所以就出现阻塞.开通一个端口来传输数据
            //设置为主动
//            ftp.enterLocalActiveMode();
//            logger.info(url + " current getDataConnectionMode: " + ftp.getDataConnectionMode());

            ftp.setFileType(FTP.BINARY_FILE_TYPE);
            boolean changeWorkingDirectory = ftp.changeWorkingDirectory(remotePath); //转移到FTP服务器目录
//            logger.debug(url + " 切换目录：" + changeWorkingDirectory + " ,上传路径：" + remotePath);
            if (!changeWorkingDirectory) {
                ftp.logout();
                ftp.disconnect();
                logger.info(url + " ftp changeWorkingDirectory failed.");
                return success;
            }
            List dfile = new ArrayList<String>();
            for (String fileName : fileNames) {
                try {
//                    logger.debug(url + " delete file");
                    //upload dwd file
                    boolean flag = false;
                    while (!ftp.deleteFile(fileName)) {
                        logger.info("delete file :" + fileName + " Retry");
                        FTPFile[] fs0 = ftp.listFiles();
                        for (FTPFile f : fs0) {
                            if (fileName.equals(f.getName())) {
                                logger.info(url + " " + fileName + "  " + " delete sucess!");
                                return true;
                            }
                        }
                        
                    }
                    flag = true;
                    if (flag) {
                        dfile.add(fileName);
                        success = true;
                    }
                    logger.info(url + " " + fileName + "  " + " delete sucess!");

                } catch (Exception ex) {
                    logger.error(url + " " + remotePath + " delete err!" + ex.getMessage(), ex);
                } finally {
                }
            }

            ftp.logout();
        } catch (Exception e) {
            logger.error(url + " ftp upload err " + e.getMessage(), e);
        } finally {
            if (ftp.isConnected()) {
                try {
                    ftp.disconnect();
                } catch (IOException ioe) {
                    logger.error(url + " " + ioe.getMessage(), ioe);
                }
            }
        }
        return success;
    }

    //ftp上传.ok文件
    public boolean okFile(String url, int port, String username, String password, String remotePath, String fileName) {
        boolean success = false;
        FTPClient ftp = new FTPClient();
        try {
            int reply;
            ftp.connect(url, port);
            //如果采用默认端口，可以使用ftp.connect(url)的方式直接连接FTP服务器
            ftp.login(username, password);//登录
            ftp.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out)));
            reply = ftp.getReplyCode();
            logger.info(url + " reply: " + reply);
            if (!FTPReply.isPositiveCompletion(reply)) {
                logger.info(url + " if (!FTPReply.isPositiveCompletion(reply)) {");
                ftp.disconnect();
                logger.info(url + " ftp login err!username=" + username + ",password=" + password);
                return success;
            }

            logger.info(url + " current getDataConnectionMode: " + ftp.getDataConnectionMode());
            ftp.enterLocalPassiveMode();
            //设置为主动
//            ftp.enterLocalActiveMode();
            logger.info(url + " current getDataConnectionMode: " + ftp.getDataConnectionMode());

            boolean activeFlag = false;
            try {
                FTPFile[] fs0 = ftp.listFiles();
                logger.info(url + " ftp list size is " + fs0.length);
            } catch (Exception e) {
                logger.error(url + " ftp.listFiles error. " + e.getMessage(), e);
                activeFlag = true;
            } finally {
                if (activeFlag) {
                    ftp.enterLocalActiveMode();
//                    ftp.enterLocalPassiveMode();//在linux上，由于安全限制，可能某些端口没有开启，所以就出现阻塞.开通一个端口来传输数据
                    logger.info(url + " current getDataConnectionMode: " + ftp.getDataConnectionMode());
                }
            }
            ftp.setControlEncoding("UTF-8");
            ftp.setFileType(FTP.BINARY_FILE_TYPE);
            boolean changeWorkingDirectory = ftp.changeWorkingDirectory(remotePath); //转移到FTP服务器目录
            logger.debug(url + " 切换目录：" + changeWorkingDirectory + " ,上传路径：" + remotePath);
            if (!changeWorkingDirectory) {
                ftp.logout();
                ftp.disconnect();
                logger.info(url + " ftp changeWorkingDirectory failed.");
                return success;
            }

            InputStream ok = null;
            try {
                ok = new ByteArrayInputStream("ok".getBytes("utf-8"));
                boolean storeFile = ftp.storeFile(fileName + ".ok", ok);
                if (storeFile) {
                    logger.info(url + " " + fileName + ".ok" + " uplaod sucess!");
                    success = true;
                } else {
                    logger.info(url + " " + fileName + ".ok" + " uplaod error! Retry");
                    boolean fl = ftp.storeFile(fileName + ".ok", ok);
                    logger.info(url + " " + fileName + ".ok" + " uplaod return " + fl + " !");
                    if (fl) {
                        success = true;
                    } else {
                        success = false;
                    }
                }
            } catch (Exception ex) {
                logger.error(url + " upload err!" + ex.getMessage(), ex);
            } finally {
                if (ok != null) {
                    try {
                        ok.close();
                    } catch (Exception e) {
                    }
                }
            }
            ftp.logout();
        } catch (Exception e) {
            logger.error(url + " ftp upload err " + e.getMessage(), e);
        } finally {
            if (ftp.isConnected()) {
                try {
                    ftp.disconnect();
                } catch (IOException ioe) {
                    logger.error(url + " " + ioe.getMessage(), ioe);
                }
            }
        }
        return success;
    }

    //ftp上传文件,并创建多级目录
    public boolean upload(String url, int port, String username, String password, String localPath, String remotePath, String subdirectory, String fileName) {
        boolean success = false;
        FTPClient ftp = new FTPClient();
        try {

            int reply;
            ftp.connect(url, port);
            //如果采用默认端口，可以使用ftp.connect(url)的方式直接连接FTP服务器
            ftp.login(username, password);//登录
            ftp.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out)));
            reply = ftp.getReplyCode();
            logger.info(url + " reply: " + reply);
            if (!FTPReply.isPositiveCompletion(reply)) {
                logger.info(url + " if (!FTPReply.isPositiveCompletion(reply)) {");
                ftp.disconnect();
                logger.info(url + " ftp login err!username=" + username + ",password=" + password);
                return success;
            }

            ftp.setControlEncoding("UTF-8");
            ftp.setFileType(FTP.BINARY_FILE_TYPE);
            logger.info(url + " current getDataConnectionMode: " + ftp.getDataConnectionMode());
            ftp.enterLocalPassiveMode();
            //设置为主动
//            ftp.enterLocalActiveMode();
            logger.info(url + " current getDataConnectionMode: " + ftp.getDataConnectionMode());

            boolean activeFlag = false;
            try {
                FTPFile[] fs0 = ftp.listFiles();
                logger.info(url + " ftp list size is " + fs0.length);
            } catch (Exception e) {
                logger.error(url + " ftp.listFiles error. " + e.getMessage(), e);
                activeFlag = true;
            } finally {
                if (activeFlag) {
                    ftp.enterLocalActiveMode();
//                    ftp.enterLocalPassiveMode();//在linux上，由于安全限制，可能某些端口没有开启，所以就出现阻塞.开通一个端口来传输数据
                    logger.info(url + " current getDataConnectionMode: " + ftp.getDataConnectionMode());
                }
            }

            //创建目录
            boolean changeWorkingDirectory = ftp.changeWorkingDirectory(remotePath);
            if (!changeWorkingDirectory) {
                ftp.makeDirectory(remotePath);
                changeWorkingDirectory = ftp.changeWorkingDirectory(remotePath);
            }
            logger.debug(url + " 切换目录：" + changeWorkingDirectory + " ,上传路径：" + remotePath);
            logger.info(url + " remotePath：" + remotePath + "-------------" + changeWorkingDirectory);

            boolean changeflag = false;
            subdirectory = subdirectory.replaceAll("//", "/");
            if (subdirectory.startsWith("/")) {
                subdirectory = subdirectory.substring(subdirectory.indexOf("/") + 1, subdirectory.length());
            }
            if (subdirectory.endsWith("/")) {
                subdirectory = subdirectory.substring(0, subdirectory.lastIndexOf("/"));
            }
            String[] str = subdirectory.split("/");
            for (int i = 0; i < str.length; i++) {
                String path = str[i];
                boolean makeDirectory = ftp.makeDirectory(path);
                changeflag = ftp.changeWorkingDirectory(path);
                logger.info(url + " path=" + path + " ,创建目录：" + makeDirectory + " ,切换目录： " + changeflag);
            }

            if (changeflag) {
                FileInputStream in = null;
                try {
                    //upload dwd file
                    in = new FileInputStream(new File(localPath));
                    boolean storeFile = ftp.storeFile(fileName, in);
                    if (storeFile) {
                        logger.info(url + " " + fileName + " uplaod sucess!");
                        success = true;
                    } else {
                        logger.info(url + " " + fileName + " uplaod error! Retry");
                        boolean fl = ftp.storeFile(fileName, in);
                        logger.info(url + " " + fileName + " uplaod return " + fl + " !");
                        if (fl) {
                            success = true;
                        } else {
                            success = false;
                        }
                    }
                } catch (Exception ex) {
                    logger.error(localPath + " upload err!" + ex.getMessage(), ex);
                } finally {
                    if (in != null) {
                        try {
                            in.close();
                        } catch (Exception e) {
                        }
                    }
                }
            }
            ftp.logout();
        } catch (Exception e) {
            logger.error(url + " ftp upload err " + e.getMessage(), e);
        } finally {
            if (ftp.isConnected()) {
                try {
                    ftp.disconnect();
                } catch (IOException ioe) {
                    logger.error(url + " " + ioe.getMessage(), ioe);
                }
            }
        }
        return success;
    }

    public boolean downDataFile1(FTPClient ftp, String url, String remotePath, String localPath, String filetype) {
        logger.info("FtpTools downFile start");
        boolean success = false;
        try {
            logger.info(url + " current getDataConnectionMode: " + ftp.getDataConnectionMode());
//            ftp.enterLocalActiveMode();//设置为主动
            ftp.enterLocalPassiveMode();//在linux上，由于安全限制，可能某些端口没有开启，所以就出现阻塞.开通一个端口来传输数据
            logger.info(url + " current getDataConnectionMode: " + ftp.getDataConnectionMode());

            boolean activeFlag = false;
            try {
                FTPFile[] fs0 = ftp.listFiles();
                logger.debug(url + " ftp list size is " + fs0.length);
            } catch (Exception e) {
                logger.error(url + " ftp.listFiles error. " + e.getMessage(), e);
                activeFlag = true;
            } finally {
                if (activeFlag) {
                    ftp.enterLocalActiveMode();//设置为主动
//                    ftp.enterLocalPassiveMode();//在linux上，由于安全限制，可能某些端口没有开启，所以就出现阻塞.开通一个端口来传输数据
                    logger.info(url + " current getDataConnectionMode: " + ftp.getDataConnectionMode());
                }
            }

            ftp.setDataTimeout(1800000);//ms
            ftp.setFileType(FTP.BINARY_FILE_TYPE);
            String printWorkingDirectory = ftp.printWorkingDirectory();
            logger.info(url + " 当前工作路径 " + printWorkingDirectory);
            if (!printWorkingDirectory.endsWith(remotePath)) {
                boolean changeWorkingDirectory = ftp.changeWorkingDirectory(remotePath); //转移到FTP服务器目录
                logger.debug("切换目录：" + changeWorkingDirectory + " ,下载路径：" + remotePath);
            }

            OutputStream is = null;
            try {
                File rootDir = new File(localPath);
                if (!rootDir.exists()) {
                    rootDir.mkdirs();
                }
                File localFile = new File(localPath + "/" + filetype);
                is = new FileOutputStream(localFile);
                boolean retrieveFile = ftp.retrieveFile(filetype, is);
                if (retrieveFile) {
                    logger.info(url + " " + filetype + " download sucess!");
                    success = true;
                } else {
                    logger.info(url + " " + filetype + " download error! Retry");
                    boolean fl = ftp.retrieveFile(filetype, is);
                    logger.info(url + " " + filetype + " download return " + fl + " !");
                    if (fl) {
                        success = true;
                    } else {
                        success = false;
                    }
                }
            } catch (Exception ex) {
                logger.error(filetype + " download err!" + ex.getMessage(), ex);
            } finally {
                if (is != null) {
                    try {
                        is.close();
                    } catch (Exception e) {
                    }
                }
            }
        } catch (Exception e) {
            logger.error(url + " ftp download err " + e.getMessage(), e);
        }
        logger.info(url + " ftp download finish!");
        return success;
    }

    public String downDataFile(FTPClient ftp, String url, String remotePath, String localPath, String filetype) {
        logger.info("FtpTools downFile start");
        String success = "false";
        try {
            logger.info(url + " current getDataConnectionMode: " + ftp.getDataConnectionMode());
//            ftp.enterLocalActiveMode();//设置为主动
            ftp.enterLocalPassiveMode();//在linux上，由于安全限制，可能某些端口没有开启，所以就出现阻塞.开通一个端口来传输数据
            logger.info(url + " current getDataConnectionMode: " + ftp.getDataConnectionMode());

            boolean activeFlag = false;
            try {
                FTPFile[] fs0 = ftp.listFiles();
                logger.debug(url + " ftp list size is " + fs0.length);
            } catch (Exception e) {
                logger.error(url + " ftp.listFiles error. " + e.getMessage(), e);
                activeFlag = true;
            } finally {
                if (activeFlag) {
                    ftp.enterLocalActiveMode();//设置为主动
//                    ftp.enterLocalPassiveMode();//在linux上，由于安全限制，可能某些端口没有开启，所以就出现阻塞.开通一个端口来传输数据
                    logger.info(url + " current getDataConnectionMode: " + ftp.getDataConnectionMode());
                }
            }

//            if (url.equals("10.139.36.2")) {
            ftp.setDataTimeout(1200000);//数据传输超时时间1200ms
//            }

            try {
                ftp.setFileType(FTP.BINARY_FILE_TYPE);
            } catch (Exception ex) {
                logger.error(url + " " + filetype + " download err!" + ex.getMessage(), ex);
                success = "ERROR";
                return success;
            }

            String printWorkingDirectory = ftp.printWorkingDirectory();
            logger.info(url + " 当前工作路径 " + printWorkingDirectory);
            if (!printWorkingDirectory.endsWith(remotePath)) {
                boolean changeWorkingDirectory = ftp.changeWorkingDirectory(remotePath); //转移到FTP服务器目录
                logger.debug("切换目录：" + changeWorkingDirectory + " ,下载路径：" + remotePath);
            }

            OutputStream is = null;
            try {
                File rootDir = new File(localPath);
                if (!rootDir.exists()) {
                    rootDir.mkdirs();
                }
                File localFile = new File(localPath + "/" + filetype);
                is = new FileOutputStream(localFile);
                boolean retrieveFile = ftp.retrieveFile(filetype, is);
                if (retrieveFile) {
                    logger.info(url + " " + filetype + " download sucess!");
                    success = "true";
                } else {
                    logger.info(url + " " + filetype + " download error! Retry");
                    boolean fl = ftp.retrieveFile(filetype, is);
                    logger.info(url + " " + filetype + " download return " + fl + " !");
                    if (fl) {
                        success = "true";
                    } else {
                        success = "false";
                    }
                }
            } catch (Exception ex) {
                logger.error(url + " " + filetype + " download err!" + ex.getMessage(), ex);
                success = "ERROR";
            } finally {
                if (is != null) {
                    try {
                        is.close();
                    } catch (Exception e) {
                    }
                }
            }
        } catch (Exception e) {
            logger.error(url + " ftp download err " + e.getMessage(), e);
        }
        logger.info(url + " ftp download finish!");
        return success;
    }

    public String downDataFile2(FTPClient ftp, String url, String remotePath, String localPath, String filetype) {
        logger.info("FtpTools downFile start");
        String success = "false";
        try {
            logger.info(url + " current getDataConnectionMode: " + ftp.getDataConnectionMode());
//            ftp.enterLocalActiveMode();//设置为主动
            ftp.enterLocalPassiveMode();//在linux上，由于安全限制，可能某些端口没有开启，所以就出现阻塞.开通一个端口来传输数据
            logger.info(url + " current getDataConnectionMode: " + ftp.getDataConnectionMode());

            boolean activeFlag = false;
            try {
                FTPFile[] fs0 = ftp.listFiles();
                logger.debug(url + " ftp list size is " + fs0.length);
            } catch (Exception e) {
                logger.error(url + " ftp.listFiles error. " + e.getMessage(), e);
                activeFlag = true;
            } finally {
                if (activeFlag) {
                    ftp.enterLocalActiveMode();//设置为主动
//                    ftp.enterLocalPassiveMode();//在linux上，由于安全限制，可能某些端口没有开启，所以就出现阻塞.开通一个端口来传输数据
                    logger.info(url + " current getDataConnectionMode: " + ftp.getDataConnectionMode());
                }
            }

            ftp.setDataTimeout(1200000);//ms
            ftp.setFileType(FTP.BINARY_FILE_TYPE);
            String printWorkingDirectory = ftp.printWorkingDirectory();
            logger.info(url + " 当前工作路径 " + printWorkingDirectory);
            if (!printWorkingDirectory.endsWith(remotePath)) {
                boolean changeWorkingDirectory = ftp.changeWorkingDirectory(remotePath); //转移到FTP服务器目录
                logger.debug("切换目录：" + changeWorkingDirectory + " ,下载路径：" + remotePath);
            }

            OutputStream is = null;
            try {
                File rootDir = new File(localPath);
                if (!rootDir.exists()) {
                    rootDir.mkdirs();
                }
                File localFile = new File(localPath + "/" + filetype);
                is = new FileOutputStream(localFile);
                boolean retrieveFile = ftp.retrieveFile(filetype, is);
                if (retrieveFile) {
                    logger.info(url + " " + filetype + " download sucess!");
                    success = "true";
                } else {
                    logger.info(url + " " + filetype + " download error! Retry");
                    boolean fl = ftp.retrieveFile(filetype, is);
                    logger.info(url + " " + filetype + " download return " + fl + " !");
                    if (fl) {
                        success = "true";
                    } else {
                        success = "false";
                    }
                }
            } catch (Exception ex) {
                logger.error(filetype + " download err!" + ex.getMessage(), ex);
                success = "ERROR";
            } finally {
                if (is != null) {
                    try {
                        is.close();
                    } catch (Exception e) {
                    }
                }
            }
        } catch (Exception e) {
            logger.error(url + " ftp download err " + e.getMessage(), e);
        }
        logger.info(url + " ftp download finish!");
        return success;
    }

    public FTPClient createFtpClient(String url, int port, String username, String password) {
        logger.info(url + " begin to create ftpClient. and the ip is " + url + ",port is " + port + ",username is " + ",password is " + password);
        FTPClient ftp = new FTPClient();
        try {
            int reply;
            logger.debug(url + " begin to connect FTPClient.");
            ftp.connect(url, port);
            logger.debug(url + " connect ftp successfulley. And begin to login.");
            //如果采用默认端口，可以使用ftp.connect(url)的方式直接连接FTP服务器
            ftp.login(username, password);//登录
            logger.debug(url + " login FTP successfully.");
            reply = ftp.getReplyCode();
            if (!FTPReply.isPositiveCompletion(reply)) {
                ftp.disconnect();
                logger.info(url + " " + url + "ftp login err!username=" + username + ",password=" + password);
                return null;
            }
            logger.info(url + " create ftpClient successfully.");
        } catch (Exception e) {
            logger.error(e.getMessage() + e);
            return null;
        }
        return ftp;
    }

    public void destroyFtpClient(FTPClient ftpClient) {
        try {
            if (ftpClient != null && ftpClient.isConnected()) {
                ftpClient.logout();
            }
        } catch (Exception e) {
            logger.error(" ftp client logout failed." + e.getMessage(), e);
        } finally {
            if (ftpClient != null) {
                try {
                    ftpClient.disconnect();
                } catch (IOException ex) {
                    logger.error(" ftp client disconnect failed." + ex.getMessage(), ex);
                }
            }
        }
    }

}
